﻿using System;
using System.IO;
using CSharpHelpers.Encrypts;

namespace CSharpHelpers.IOs
{
    public abstract class FileUtil
    {
        /// <summary>
        /// 加载文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="falg">是否加密</param>
        /// <returns></returns>
        public static bool CheckFileIsEncrypted(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = null;
            try
            {
                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];                  // create buffer
                int count;                                                    // actual number of bytes read
                int sum = 0;                                                // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading
                }
                if (EncryptHelper.IsEncrypted(buffer))//如果加密
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                FileLog.LogError(ex);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }

                buffer = null;
            }

            return false;
        }

        /// <summary>
        ///写临时文件
        /// </summary>
        /// <param name="buffer"></param>
        public static void WriteBakFile(byte[] buffer, string filePath, string bakFileName)
        {
            FileStream aFile = null;
            try
            {
                int index = filePath.IndexOf(bakFileName);
                if (index > -1)
                {
                    var tempFileName = filePath.Remove(index, filePath.Length - index);
                    if (!Directory.Exists(tempFileName))
                    {

                        Directory.CreateDirectory(tempFileName);
                    }

                    aFile = new FileStream(filePath, FileMode.Create);
                    aFile.Write(buffer, 0, buffer.Length);
                }

            }
            catch (Exception ex)
            {
                FileLog.LogError(ex);
            }
            finally
            {
                if (aFile != null)
                    aFile.Close();
            }
        }


        /// <summary>
        /// 删除临时文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void DeleteFile(string filePath)
        {
            File.Delete(filePath);
        }

        /// <summary>
        ///加载INI，用于加解密
        /// </summary>
        /// <returns></returns>
        public static byte[] LocalBAKXML(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = null;
            try
            {

                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading
                }
            }
            catch (Exception ex)
            {
                buffer = new byte[] { };
                FileLog.LogError(ex);
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }
            return buffer;
        }

        /// <summary>
        /// 加载文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="falg">是否加密</param>
        /// <returns></returns>
        public static byte[] LocalIni(string filePath, bool falg = false)
        {
            byte[] buffer;
            FileStream fileStream = null;
            try
            {

                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading
                }
                if (EncryptHelper.IsEncrypted(buffer))//如果加密
                {
                    if (falg)
                    {
                        buffer = EncryptHelper.Decrypt(buffer);
                    }
                }
                else
                {
                    if (falg)
                    {
                        buffer = EncryptHelper.Encrypt(buffer);
                    }
                }
            }
            catch (Exception ex)
            {
                buffer = new byte[] { };
                FileLog.LogError(ex);
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }
            return buffer;
        }

        /// <summary>
        /// 写加密或解密后的文件
        /// </summary>
        /// <returns></returns>
        public static void WriteINI(byte[] buffer, string filePath)
        {
            FileStream aFile = new FileStream(filePath, FileMode.Create);
            aFile.Write(buffer, 0, buffer.Length);
            aFile.Close();
        }


        /// <summary>
        /// 纯读文件方法,把文件加载到内存中
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static byte[] ReadFile(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = null;
            try
            {

                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading
                }
            }
            catch (Exception ex)
            {
                buffer = new byte[] { };
                FileLog.LogError(ex);
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }
            return buffer;
        }


        /// <summary>
        ///  加密文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static byte[] EncryptionReadFile(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = null;
            try
            {

                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading
                }
                if (!EncryptHelper.IsEncrypted(buffer))//如果加密
                {
                    buffer = EncryptHelper.Encrypt(buffer);
                }
            }
            catch (Exception ex)
            {
                buffer = null;
                FileLog.LogError(ex);
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }
            return buffer;
        }

        /// <summary>
        ///  加密文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static byte[] DecryptReadFile(string filePath)
        {
            byte[] buffer;
            FileStream fileStream = null;
            try
            {

                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                int length = (int)fileStream.Length;  // get file length
                buffer = new byte[length];            // create buffer
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading
                }
                if (EncryptHelper.IsEncrypted(buffer))//如果加密
                {
                    buffer = EncryptHelper.Decrypt(buffer);
                }
            }
            catch (Exception ex)
            {
                buffer = null;
                FileLog.LogError(ex);
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }
            return buffer;
        }
    }
}
